#!/usr/bin/env ruby
# encoding: utf-8

require "net/http"
require "json"
require "logger"
require 'fileutils'

API_KEY =  "0b64a6418fd61e33222df2c4af825a99"
DOUBAN_API = "https://api.douban.com/v2/movie/subject"

unless File.exist? "call_api.log"
  FileUtils.touch('call_api.log')
end

$logger = Logger.new(File.open('call_api.log', File::WRONLY | File::APPEND))

def call_api(movie_id) 
  res_uri = URI("#{DOUBAN_API}/#{movie_id}?apikey=#{API_KEY}")
  puts res_uri

  begin
    movie = parse_response(Net::HTTP.get(res_uri))
  rescue Exception => e
    $logger.error("id:#{movie_id}")
    return nil
  end

  return  movie
end

def parse_response(response)
  movie = JSON.parse(response)
  return movie
end

def save_database(movie)
  # TODO save to mongodb
  return if movie.nil?
  puts movie["title"]
end

def main
  File.open("./res.txt")  do |file| 
    while(line = file.gets)
      id = line.strip
      movie = call_api(id)
      save_database(movie)
      sleep(1)
    end
  end
end

main()
